using System;
using System.Collections.Generic;
using System.Text;

namespace TotalCommander_v3
{
    class ListViewItemComparer:System.Collections.IComparer
    {
        private int col;
        private System.Windows.Forms.SortOrder order;

        public ListViewItemComparer()
        {
            col = 0;
            order = System.Windows.Forms.SortOrder.Ascending;
        }
        public ListViewItemComparer(int column, System.Windows.Forms.SortOrder order)
        {
            col = column;
            this.order = order;
        }

        public int Compare(object x, object y)
        {
            int returnVal = 0;
            if(!(((System.Windows.Forms.ListViewItem)x).SubItems[2].Text == " " && ((System.Windows.Forms.ListViewItem)y).SubItems[2].Text == " " ))
            {
                return 1;
            }
            string xValue = ((System.Windows.Forms.ListViewItem)x).SubItems[col].Text;
            string yValue = ((System.Windows.Forms.ListViewItem)y).SubItems[col].Text;
            if (col == 0)
            {
                returnVal = String.Compare(xValue, yValue);
                 if (order == System.Windows.Forms.SortOrder.Descending)
                     returnVal *= -1;
                return returnVal;

            }
            else if (col == 1)
            {
                xValue = xValue.Substring(0, xValue.Length - 2);
                yValue = yValue.Substring(0, yValue.Length - 2);
                if(Int32.Parse(xValue) > Int32.Parse(yValue))
                {
                    returnVal = 1;
                }
                else if(Int32.Parse(xValue) < Int32.Parse(yValue))
                {
                    returnVal = -1;
                }
                
                if (order == System.Windows.Forms.SortOrder.Descending)
                    returnVal *= -1;
                return returnVal;
            }
            else if (col == 3)
            {
                try
                {
                    System.DateTime firstDate =
                            DateTime.Parse(((System.Windows.Forms.ListViewItem)x).SubItems[col].Text);
                    System.DateTime secondDate =
                            DateTime.Parse(((System.Windows.Forms.ListViewItem)y).SubItems[col].Text);
                    returnVal = DateTime.Compare(firstDate, secondDate);
                }
                catch
                {
                    returnVal = String.Compare(((System.Windows.Forms.ListViewItem)x).SubItems[col].Text,
                                ((System.Windows.Forms.ListViewItem)y).SubItems[col].Text);
                }
                if (order == System.Windows.Forms.SortOrder.Descending)
                    returnVal *= -1;
                return returnVal;

            }
            return 0;
        }

    }
}
